<!--

    Copyright © 2016-2024 The Thingsboard Authors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<div class="connector-container tb-form-panel no-border">
  <section class="table-section tb-form-panel no-padding flex section-container">
    <mat-toolbar class="mat-mdc-table-toolbar">
      <h2>{{ 'gateway.connectors' | translate }}</h2>
      <span fxFlex></span>
      <button mat-icon-button
              [disabled]="isLoading$ | async"
              (click)="addConnector($event)"
              matTooltip="{{ 'action.add' | translate }}"
              matTooltipPosition="above">
        <mat-icon>add</mat-icon>
      </button>
    </mat-toolbar>
    <div class="table-container">
      <section *ngIf="!dataSource?.data?.length" fxLayoutAlign="center center"
               class="mat-headline-5 tb-absolute-fill tb-add-new">
        <button mat-button class="connector"
        (click)="addConnector($event)">
          <mat-icon class="tb-mat-96">add</mat-icon>
          <span>{{ 'gateway.add-connector' | translate }}</span>
        </button>
      </section>
      <table mat-table [dataSource]="dataSource"
             matSort [matSortActive]="pageLink.sortOrder.property" [matSortDirection]="pageLink.sortDirection()"
             matSortDisableClear>
        <ng-container matColumnDef="enabled" sticky>
          <mat-header-cell *matHeaderCellDef style="width: 60px;min-width: 60px;">
            {{ 'gateway.connectors-table-enabled' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute">
            <mat-slide-toggle [checked]="activeConnectors.includes(attribute.key)"
                              (click)="$event.stopPropagation(); enableConnector(attribute)"></mat-slide-toggle>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="key">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 40%">
            {{ 'gateway.connectors-table-name' | translate }}</mat-header-cell>
          <mat-cell *matCellDef="let attribute">
            {{ attribute.key }}
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="type">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.connectors-table-type' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
            {{ returnType(attribute) }}
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="syncStatus">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.configuration' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
              <div class="status" [class]="isConnectorSynced(attribute) ? 'status-sync' : 'status-unsync'">
                {{ isConnectorSynced(attribute) ? 'sync' : 'out of sync' }}
              </div>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="errors">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.connectors-table-status' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
            <span class="dot"
                  matTooltip="{{ 'Errors: '+ getErrorsCount(attribute)}}"
                  matTooltipPosition="above"
                  (click)="connectorLogs(attribute, $event)"
                  [class]="{'hasErrors': +getErrorsCount(attribute) > 0,
                            'noErrors': +getErrorsCount(attribute) === 0 || getErrorsCount(attribute) === ''}"></span>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="actions" stickyEnd>
          <mat-header-cell *matHeaderCellDef
                           [ngStyle.gt-md]="{ minWidth: '144px', maxWidth: '144px', width: '144px', textAlign: 'center'}">
            {{ 'gateway.connectors-table-actions' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute"
                    [ngStyle.gt-md]="{ minWidth: '144px', maxWidth: '144px', width: '144px'}">
            <div fxHide fxShow.gt-md fxFlex fxLayout="row" fxLayoutAlign="end">
              <button mat-icon-button
                      matTooltip="RPC"
                      matTooltipPosition="above"
                      (click)="connectorRpc(attribute, $event)">
                <mat-icon>private_connectivity</mat-icon>
              </button>
              <button mat-icon-button
                      matTooltip="Logs"
                      matTooltipPosition="above"
                      (click)="connectorLogs(attribute, $event)">
                <mat-icon>list</mat-icon>
              </button>
              <button mat-icon-button
                      matTooltip="Delete connector"
                      matTooltipPosition="above"
                      (click)="deleteConnector(attribute, $event)">
                <mat-icon>delete</mat-icon>
              </button>
            </div>
            <div fxHide fxShow.lt-lg>
              <button mat-icon-button
                      (click)="$event.stopPropagation()"
                      [matMenuTriggerFor]="cellActionsMenu">
                <mat-icon class="material-icons">more_vert</mat-icon>
              </button>
              <mat-menu #cellActionsMenu="matMenu" xPosition="before">
                <button mat-icon-button
                        matTooltip="RPC"
                        matTooltipPosition="above"
                        (click)="connectorRpc(attribute, $event)">
                  <mat-icon>private_connectivity</mat-icon>
                </button>
                <button mat-icon-button
                        matTooltip="Logs"
                        matTooltipPosition="above"
                        (click)="connectorLogs(attribute, $event)">
                  <mat-icon>list</mat-icon>
                </button>
                <button mat-icon-button
                        matTooltip="Delete connector"
                        matTooltipPosition="above"
                        (click)="deleteConnector(attribute, $event)">
                  <mat-icon>delete</mat-icon>
                </button>
              </mat-menu>
            </div>
          </mat-cell>
        </ng-container>
        <mat-header-row class="mat-row-select"
                        *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
        <mat-row class="mat-row-select" [class]="{'tb-current-entity': isSameConnector(attribute)}"
                 *matRowDef="let attribute; let i = index; columns: displayedColumns;" (click)="selectConnector($event, attribute)"></mat-row>
      </table>
    </div>
  </section>
  <section [formGroup]="connectorForm" class="tb-form-panel section-container flex">
    <div class="tb-form-panel-title tb-flex no-flex space-between align-center">
      <div class="tb-form-panel-title">
        {{ initialConnector?.type ? gatewayConnectorDefaultTypes.get(initialConnector.type) : '' }}
        {{ 'gateway.configuration' | translate }}
      </div>
      <tb-toggle-select *ngIf="initialConnector && initialConnector.type === connectorType.MQTT" formControlName="mode" appearance="fill">
        <tb-toggle-option [value]="connectorConfigurationModes.BASIC">
          {{ 'gateway.basic' | translate }}
        </tb-toggle-option>
        <tb-toggle-option [value]="connectorConfigurationModes.ADVANCED">
          {{ 'gateway.advanced' | translate }}
        </tb-toggle-option>
      </tb-toggle-select>
    </div>
    <span [fxShow]="!initialConnector"
          fxLayoutAlign="center center"
          class="no-data-found" translate>
      gateway.select-connector
    </span>
    <section class="tb-form-panel section-container no-border no-padding tb-flex space-between" *ngIf="initialConnector">
      <mat-tab-group>
        <mat-tab label="{{ 'gateway.general' | translate }}">
          <div class="tb-form-panel no-border no-padding padding-top">
            <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
              <div class="fixed-title-width tb-required" translate>gateway.name</div>
              <div class="tb-flex no-gap">
                <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                  <input matInput name="value" formControlName="name" placeholder="{{ 'gateway.set' | translate }}"/>
                  <mat-icon matSuffix
                            matTooltipPosition="above"
                            matTooltipClass="tb-error-tooltip"
                            [matTooltip]="('gateway.name-required') | translate"
                            *ngIf="connectorForm.get('name').hasError('required') && connectorForm.get('name').touched"
                            class="tb-error">
                    warning
                  </mat-icon>
                </mat-form-field>
              </div>
            </div>
            <div class="tb-form-panel stroked">
              <div class="tb-form-panel-title" translate>gateway.logs-configuration</div>
              <div class="tb-form-row" fxLayoutAlign="space-between center">
                <mat-slide-toggle class="mat-slide" formControlName="enableRemoteLogging">
                  <mat-label>
                    {{ 'gateway.enable-remote-logging' | translate }}
                  </mat-label>
                </mat-slide-toggle>
              </div>
              <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                <div class="fixed-title-width" translate>gateway.remote-logging-level</div>
                <div class="tb-flex no-gap">
                  <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                    <mat-select formControlName="logLevel">
                      <mat-option *ngFor="let logLevel of gatewayLogLevel" [value]="logLevel">{{ logLevel }}</mat-option>
                    </mat-select>
                  </mat-form-field>
                </div>
              </div>
            </div>
            <div *ngIf="connectorForm.get('type').value === connectorType.MQTT" class="tb-form-row column-xs" fxLayoutAlign="space-between center">
              <mat-slide-toggle class="mat-slide" formControlName="sendDataOnlyOnChange">
                <mat-label tb-hint-tooltip-icon="{{ 'gateway.send-change-data-hint' | translate }}">
                  {{ 'gateway.send-change-data' | translate }}
                </mat-label>
              </mat-slide-toggle>
            </div>
          </div>
        </mat-tab>
        <ng-container *ngIf="connectorForm.get('type').value === connectorType.MQTT &&
                             connectorForm.get('mode').value === connectorConfigurationModes.BASIC; else defaultConfig"
                      formGroupName="basicConfig">
          <mat-tab label="{{ 'gateway.broker.connection' | translate }}*">
            <ng-container formGroupName="broker">
              <div class="tb-form-panel no-border no-padding padding-top">
                <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                  <div class="fixed-title-width tb-required" translate>gateway.host</div>
                  <div class="tb-flex no-gap">
                    <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                      <input matInput name="value" formControlName="host" placeholder="{{ 'gateway.set' | translate }}"/>
                      <mat-icon matSuffix
                                matTooltipPosition="above"
                                matTooltipClass="tb-error-tooltip"
                                [matTooltip]="('gateway.host-required') | translate"
                                *ngIf="connectorForm.get('basicConfig.broker.host').hasError('required')
                                       && connectorForm.get('basicConfig.broker.host').touched"
                                class="tb-error">
                        warning
                      </mat-icon>
                    </mat-form-field>
                  </div>
                </div>
                <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                  <div class="fixed-title-width tb-required" translate>gateway.port</div>
                  <div class="tb-flex no-gap">
                    <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                      <input matInput type="number" min="{{portLimits.MIN}}" max="{{portLimits.MAX}}"
                             name="value" formControlName="port" placeholder="{{ 'gateway.set' | translate }}"/>
                      <mat-icon matSuffix
                                matTooltipPosition="above"
                                matTooltipClass="tb-error-tooltip"
                                [matTooltip]="portErrorTooltip"
                                *ngIf="(connectorForm.get('basicConfig.broker.port').hasError('required') ||
                                        connectorForm.get('basicConfig.broker.port').hasError('min') ||
                                        connectorForm.get('basicConfig.broker.port').hasError('max')) &&
                                        connectorForm.get('basicConfig.broker.port').touched"
                                class="tb-error">
                        warning
                      </mat-icon>
                    </mat-form-field>
                  </div>
                </div>
                <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                  <div class="fixed-title-width" translate>gateway.mqtt-version</div>
                  <div class="tb-flex no-gap">
                    <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                      <mat-select formControlName="version">
                        <mat-option *ngFor="let version of mqttVersions" [value]="version.value">{{ version.name }}</mat-option>
                      </mat-select>
                    </mat-form-field>
                  </div>
                </div>
                <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                  <div class="fixed-title-width" translate>gateway.client-id</div>
                  <div class="tb-flex no-gap">
                    <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                      <input matInput name="value" formControlName="clientId" placeholder="{{ 'gateway.set' | translate }}"/>
                      <button type="button"
                              matSuffix
                              mat-icon-button
                              aria-label="Generate"
                              matTooltip="{{ 'gateway.generate-client-id' | translate }}"
                              matTooltipPosition="above"
                              (click)="generate('basicConfig.broker.clientId')"
                              *ngIf="!connectorForm.get('basicConfig.broker.clientId').value">
                        <mat-icon>autorenew</mat-icon>
                      </button>
                    </mat-form-field>
                  </div>
                </div>
                <tb-broker-security [formControl]="connectorForm.get('basicConfig.broker.security')">
                </tb-broker-security>
              </div>
            </ng-container>
          </mat-tab>
          <mat-tab label="{{ 'gateway.data-mapping' | translate }}*">
            <div class="tb-form-panel no-border no-padding padding-top tb-flex fill-height">
              <tb-mapping-table formControlName="dataMapping" [mappingType]="mappingTypes.DATA"></tb-mapping-table>
            </div>
          </mat-tab>
          <mat-tab label="{{ 'gateway.requests-mapping' | translate }}">
            <div class="tb-form-panel no-border no-padding padding-top tb-flex fill-height">
              <tb-mapping-table formControlName="requestsMapping" [mappingType]="mappingTypes.REQUESTS"></tb-mapping-table>
            </div>
          </mat-tab>
          <mat-tab label="{{ 'gateway.workers-settings' | translate }}">
            <div class="tb-form-panel no-border no-padding">
              <ng-container formGroupName="broker">
                <div class="tb-form-panel no-border no-padding padding-top">
                  <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                    <div class="fixed-title-width tb-required" [style.width.%]="50"
                         tb-hint-tooltip-icon="{{ 'gateway.max-number-of-workers-hint' | translate }}" translate>
                      gateway.max-number-of-workers
                    </div>
                    <div class="tb-flex no-gap">
                      <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                        <input matInput name="value" type="number" min="1" formControlName="maxNumberOfWorkers"
                               placeholder="{{ 'gateway.set' | translate }}"/>
                        <mat-icon matSuffix
                                  matTooltipPosition="above"
                                  matTooltipClass="tb-error-tooltip"
                                  [matTooltip]="('gateway.max-number-of-workers-required') | translate"
                                  *ngIf="connectorForm.get('basicConfig.broker.maxNumberOfWorkers').hasError('min') ||
                                         (connectorForm.get('basicConfig.broker.maxNumberOfWorkers').hasError('required') &&
                                         connectorForm.get('basicConfig.broker.maxNumberOfWorkers').touched)"
                                  class="tb-error">
                          warning
                        </mat-icon>
                      </mat-form-field>
                    </div>
                  </div>
                  <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
                    <div class="fixed-title-width tb-required" [style.width.%]="50"
                         tb-hint-tooltip-icon="{{ 'gateway.max-messages-queue-for-worker-hint' | translate }}" translate>
                      gateway.max-messages-queue-for-worker
                    </div>
                    <div class="tb-flex no-gap">
                      <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
                        <input matInput name="value" type="number" min="1" formControlName="maxMessageNumberPerWorker"
                               placeholder="{{ 'gateway.set' | translate }}"/>
                        <mat-icon matSuffix
                                  matTooltipPosition="above"
                                  matTooltipClass="tb-error-tooltip"
                                  [matTooltip]="('gateway.max-messages-queue-for-worker-required') | translate"
                                  *ngIf="connectorForm.get('basicConfig.broker.maxMessageNumberPerWorker').hasError('min') ||
                                         (connectorForm.get('basicConfig.broker.maxMessageNumberPerWorker').hasError('required') &&
                                         connectorForm.get('basicConfig.broker.maxMessageNumberPerWorker').touched)"
                                  class="tb-error">
                          warning
                        </mat-icon>
                      </mat-form-field>
                    </div>
                  </div>
                </div>
              </ng-container>
            </div>
          </mat-tab>
        </ng-container>
        <ng-template #defaultConfig>
          <mat-tab label="{{ 'gateway.configuration' | translate }}*">
            <tb-json-object-edit
              fillHeight="true"
              class="tb-flex fill-height"
              fxLayout="column"
              jsonRequired
              label="{{ 'gateway.configuration' | translate }}"
              formControlName="configurationJson">
            </tb-json-object-edit>
          </mat-tab>
        </ng-template>
      </mat-tab-group>
      <div fxLayoutAlign="end center">
        <button mat-raised-button color="primary"
                type="button"
                [disabled]="!connectorForm.dirty || connectorForm.invalid"
                (click)="saveConnector()">
          {{ 'action.save' | translate }}
        </button>
      </div>
    </section>
  </section>
</div>
